package com.netty.cn.rpc.selfmessage;

import com.netty.cn.rpc.selfmessage.core.MyMessageDecoder;
import com.netty.cn.rpc.selfmessage.core.MyMessageEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {
    public static void main(String[] args)  {
    	
    	int port=8080;
    	
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);//处理连接请求
        EventLoopGroup workerGroup=new NioEventLoopGroup();//默认线程数量为cpu核数的两倍，处理业务
        try {
            ServerBootstrap bootstrap=new ServerBootstrap();//创建服务器端的启动对象
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,port)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline channelPipeline=socketChannel.pipeline();
                            channelPipeline.addLast(new MyMessageDecoder());//加解码器
                            channelPipeline.addLast(new MyMessageEncoder());
                            channelPipeline.addLast(new MyServerHandler());
                        }
                    });
            System.out.println("netty server start");
            //启动服务器绑定端口，bind是异步操作，sync是等待
            ChannelFuture cf=bootstrap.bind(port).sync();
 
            cf.channel().closeFuture().sync();
        }catch(Exception e){
//        	log.error(e.toString(),e);
        	System.out.println(e.toString());
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

